package org.example.admin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.admin.service.AdminGoodsListService;
import org.example.common.utils.ResponseUtil;
import org.example.core.elasticsearch.service.ElasticSearchService;
import org.example.db.entity.Goods;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@RestController
@RequestMapping("/goods/list")
@Api(tags = "对商品列表的操作")
public class AdminGoodsListController {
    AdminGoodsListService adminGoodsListService;
    ElasticSearchService elasticSearchService;

    public AdminGoodsListController(AdminGoodsListService adminGoodsListService, ElasticSearchService elasticSearchService) {
        this.adminGoodsListService = adminGoodsListService;
        this.elasticSearchService = elasticSearchService;
    }

    /* 获取指定商品信息列表 */
    @GetMapping("/list")
    public Object getList(@RequestParam Integer page,@RequestParam Integer limit){
        IPage<Goods> goodsIPage = adminGoodsListService.getPageGoods(new Page<Goods>(page,limit));

        return ResponseUtil.okList(goodsIPage.getRecords(), adminGoodsListService.CountTotal());
    }

//    /* 删除商品信息 */
//    @PostMapping("/delete")
//    public Object deleteGood(@RequestBody Goods goods){
//        adminGoodsListService.deleteGoods(goods.getId());
//        return ResponseUtil.ok();
//
//    }

    /* 删除商品信息 */
    @PostMapping("/delete")
    public Object deleteGood(@RequestParam Long goodsId){
        adminGoodsListService.deleteGoods(goodsId);
        return ResponseUtil.ok();

    }

    /* 获取商品信息 */
    @GetMapping("/good")
    public Object getGood(@RequestParam Long id){
        return ResponseUtil.ok(adminGoodsListService.getGood(id));

    }

    /* 搜索商品信息 */
    @GetMapping("/search")
    @ApiOperation("搜索")
    public Object search(@RequestParam String keyword) throws IOException {

        String preTags = "<span style=\"color:red\"><b>";
        String postTags = "</b></span>";
        ArrayList<Map<String, Object>> query = elasticSearchService.query(keyword, 0, 10, preTags, postTags);
        ArrayList<Goods> goodsArrayList = new ArrayList<>();
        for(Map<String, Object> map: query){
            Goods goods = adminGoodsListService.getGood(Long.parseLong((String) map.get("id")));
            goods.setName((String)map.get("name"));
            goodsArrayList.add(goods);
        }
        return ResponseUtil.ok(goodsArrayList);
    }

}
